package GUI;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFormattedTextField;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

@SuppressWarnings("serial")
public class BiddingPane extends JPanel implements ActionListener{

	private Player owner;
	private JFormattedTextField bidField;
	private JLabel feedbackLabel, amountLabel;
	private JButton bidButton;
	
	public BiddingPane(Player owner){
		super();
		this.setBorder(new EmptyBorder(10, 10, 10, 10));
		this.owner = owner;
		bidField = new JFormattedTextField();
		feedbackLabel  = new JLabel("");
		feedbackLabel.setForeground(Color.RED);
		amountLabel = new JLabel();
		layoutComponents();
		updateAmount();
	}
	public void notifyFold(){
		owner.inactiveate();
		bidButton.setEnabled(false);
	}
	public void propagateCall(){
		if(owner.hasTurn()){
			owner.call();
		}
	}
	private void updateAmount(){
		amountLabel.setText("Amount left: "+owner.getAmtLeft());
	}
	public void prepareBid(){
		bidButton.setEnabled(owner.isActive());
	}
	private void layoutComponents(){
		this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
		bidButton = new JButton("Place Bid");
		bidButton.addActionListener(this);
		bidButton.setEnabled(false);
		add(new JLabel("My bid:"));
		add(bidField);
		add(feedbackLabel);
		add(amountLabel);
		add(bidButton);
	}
	private void processBid(int bidAmt){
		if(bidAmt > owner.getAmtLeft()){
			feedbackLabel.setText("You only have "+owner.getAmtLeft()+" left!");
		}else if(bidAmt <= 0){
			feedbackLabel.setText("Your bid cannot be that low!");
		}else if(!owner.hasTurn()){
			feedbackLabel.setText("PLEASE WAIT FOR NEXT HAND!");
		}else{
			int bid = owner.raise(bidAmt);
			updateAmount();
			String result = (bid == 0)?"Your bid is less than the MINIMUM!":"Successfully placed bid: "+bidAmt;
			feedbackLabel.setText(result);
		}
	}
	@Override
	public void actionPerformed(ActionEvent e) {
		if(bidField.getText().isEmpty()){
			feedbackLabel.setText("Bid must not be empty!");
		}
		int bidAmt;
		try{
			bidAmt = Integer.parseInt(bidField.getText());
		}catch(NumberFormatException exc){
			feedbackLabel.setText("Bid must be a NUMBER!");
			return;
		}
		processBid(bidAmt);
	}
}
